package com.py.credit.controller;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.py.credit.service.XypjRemoteBaseService;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import com.alibaba.fastjson.JSONArray;
import com.py.credit.common.logs.ExceptionLogger;
import com.py.credit.common.rest.RestServiceResult;
import com.py.credit.constant.OrgConstant;
import com.py.credit.entity.Account;
import com.py.credit.entity.Element;
import com.py.credit.entity.Organization;
import com.py.credit.entity.Personnel;
import com.py.credit.entity.SysUser;
import com.py.credit.entity.common.OptionalColumn;
import com.py.credit.entity.enums.OrgTableFieldEnum;
import com.py.credit.service.OrgService;
import com.py.credit.utils.ExcelUtil;
import com.py.credit.utils.MapCache;
import com.py.framework.core.common.Page;
import com.py.framework.core.helper.HttpServletHelper;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;

@Api(tags = "org")
@RestController
@RequestMapping(value = "/org")
public class OragnizationController {

	private static final String FRONT_B_TABLE_ID = "borglist";

	@Autowired
	private OrgService orgService;

	@Autowired
	private XypjRemoteBaseService xypjRemoteBaseService;

	@RequestMapping(value = "/addOrg.json", method = RequestMethod.POST)
	@ApiOperation(value = "添加机构", httpMethod = "POST", produces = "application/json")
	public RestServiceResult<String> addOrg(Organization org, Account account,
			@ApiParam(required = true, name = "businessLicenceFile", value = "营业执照") @RequestParam(value = "businessLicenceFile", required = true) CommonsMultipartFile businessLicenceFile,
			@ApiParam(required = true, name = "commitmentLetterFile", value = "信用承诺书") @RequestParam(value = "commitmentLetterFile", required = true) CommonsMultipartFile commitmentLetterFile,
			@ApiParam(required = true, name = "orgCodeCertificateFile", value = "组织机构代码证") @RequestParam(value = "orgCodeCertificateFile", required = true) CommonsMultipartFile orgCodeCertificateFile,
			@ApiParam(required = true, name = "taxRegisterLicenceFile", value = "税务登记证") @RequestParam(value = "taxRegisterLicenceFile", required = true) CommonsMultipartFile taxRegisterLicenceFile,
			@ApiParam(required = true, name = "accountCertificateFile", value = "银行开户证明") @RequestParam(value = "accountCertificateFile", required = true) CommonsMultipartFile accountCertificateFile,
			@ApiParam(required = false, name = "regulatorFile", value = "制度标准") @RequestParam(value = "regulatorFile", required = false) CommonsMultipartFile regulatorFile,
			@ApiParam(required = true, name = "orgCrSampleFile", value = "企业信用评价样本") @RequestParam(value = "orgCrSampleFile", required = true) CommonsMultipartFile orgCrSample)
			throws Exception {

		String orgId = orgService.addOrg(org, account, businessLicenceFile, commitmentLetterFile,
				orgCodeCertificateFile, taxRegisterLicenceFile, accountCertificateFile, regulatorFile, orgCrSample);

		return new RestServiceResult<String>(orgId);

	}

	@RequestMapping(value = "/modifyOrg.json", method = RequestMethod.POST)
	@ApiOperation(value = "修改机构", httpMethod = "POST", produces = "application/json")
	public RestServiceResult<Object> modifyOrg(Organization org,
			@ApiParam(required = false, name = "businessLicenceFile", value = "营业执照") @RequestParam(value = "businessLicenceFile", required = false) CommonsMultipartFile businessLicenceFile,
			@ApiParam(required = false, name = "commitmentLetterFile", value = "信用承诺书") @RequestParam(value = "commitmentLetterFile", required = false) CommonsMultipartFile commitmentLetterFile,
			@ApiParam(required = false, name = "orgCodeCertificateFile", value = "组织机构代码证") @RequestParam(value = "orgCodeCertificateFile", required = false) CommonsMultipartFile orgCodeCertificateFile,
			@ApiParam(required = false, name = "taxRegisterLicenceFile", value = "税务登记证") @RequestParam(value = "taxRegisterLicenceFile", required = false) CommonsMultipartFile taxRegisterLicenceFile,
			@ApiParam(required = false, name = "accountCertificateFile", value = "银行开户证明") @RequestParam(value = "accountCertificateFile", required = false) CommonsMultipartFile accountCertificateFile,
			@ApiParam(required = false, name = "regulatorFile", value = "制度标准") @RequestParam(value = "regulatorFile", required = false) CommonsMultipartFile regulatorFile,
			@ApiParam(required = false, name = "orgCrSampleFile", value = "企业信用评价样本") @RequestParam(value = "orgCrSampleFile", required = false) CommonsMultipartFile orgCrSample)
			throws Exception {
		orgService.modifyOrg(org, businessLicenceFile, commitmentLetterFile, orgCodeCertificateFile,
				taxRegisterLicenceFile, accountCertificateFile, regulatorFile, orgCrSample);
		return new RestServiceResult<Object>();

	}

	@RequestMapping(value = "/addPersonnel.json", method = RequestMethod.POST)
	@ApiOperation(value = "添加人员", httpMethod = "POST", produces = "application/json")
	public RestServiceResult<Object> addPersonnel(Personnel personnel,
			@ApiParam(required = true, name = "idCardF", value = "身份证正面") @RequestParam(value = "idCardF", required = true) CommonsMultipartFile idCardFPic,
			@ApiParam(required = true, name = "idCardB", value = "身份证反面") @RequestParam(value = "idCardB", required = true) CommonsMultipartFile idCardBPic,
			@ApiParam(required = false, name = "certificationPic", value = "资质文件") @RequestParam(value = "certificationPic", required = false) CommonsMultipartFile certificationPic)
			throws Exception {

		orgService.addPersonnel(personnel, idCardFPic, idCardBPic, certificationPic);

		return new RestServiceResult<Object>();

	}

	@RequestMapping(value = "/modifyPersonnel.json", method = RequestMethod.POST)
	@ApiOperation(value = "修改人员", httpMethod = "POST", produces = "application/json")
	public RestServiceResult<Object> modifyPersonnel(Personnel personnel,
			@ApiParam(required = false, name = "idCardF", value = "身份证正面图片") @RequestParam(value = "idCardF", required = false) CommonsMultipartFile idCardFPic,
			@ApiParam(required = false, name = "idCardB", value = "身份证反面图片") @RequestParam(value = "idCardB", required = false) CommonsMultipartFile idCardBPic,
			@ApiParam(required = false, name = "certificationPic", value = "资质文件") @RequestParam(value = "certificationPic", required = false) CommonsMultipartFile certificationPic)
			throws Exception {

		orgService.modifyPersonnel(personnel, idCardFPic, idCardBPic, certificationPic);
		return new RestServiceResult<Object>();

	}

	@ApiOperation(value = "新增页面元素", httpMethod = "POST", produces = "application/json")
	@RequestMapping(value = "/addElement.json", method = RequestMethod.POST)
	public RestServiceResult<Object> addElement(
			@ApiParam(name = "sysLogo", value = "后台log") @RequestParam(value = "sysLogo", required = false) CommonsMultipartFile sysLogo,
			@ApiParam(name = "scalingSysLogo", value = "后台log缩放") @RequestParam(value = "scalingSysLogo", required = false) CommonsMultipartFile scalingSysLogo,
			@ApiParam(name = "orgId", value = "关联机构编号", required = true) @RequestParam(required = true) String orgId)
			throws Exception {

		orgService.addElement(sysLogo, scalingSysLogo, orgId);
		return new RestServiceResult<Object>();

	}

	@ApiOperation(value = "修改页面元素", httpMethod = "POST", produces = "application/json")
	@RequestMapping(value = "/modifyElement.json", method = RequestMethod.POST)
	public RestServiceResult<Object> modifyElement(
			@ApiParam(name = "sysLogo", value = "后台logo") @RequestParam(value = "sysLogo", required = false) CommonsMultipartFile sysLogo,
			@ApiParam(name = "scalingSysLogo", value = "后台logo缩放") @RequestParam(value = "scalingSysLogo", required = false) CommonsMultipartFile scalingSysLogo,
			@ApiParam(name = "orgId", value = "关联机构编号", required = true) @RequestParam(required = true) String orgId)
			throws Exception {

		orgService.modifyElement(sysLogo, scalingSysLogo, orgId);
		return new RestServiceResult<Object>();

	}

	@RequestMapping(value = "/getBOrgList.json", method = RequestMethod.POST)
	@ApiOperation(value = "获取机构列表", httpMethod = "POST", produces = "application/json")
	public RestServiceResult<List<Map<String, Object>>> getOrgList(
			@ApiParam(required = false, name = "conditions", value = "搜索条件") String condition, Page page,

			HttpServletRequest request) {

		String[] configColumns = null;

		RestServiceResult<SysUser> user = xypjRemoteBaseService.getCurrentUser(HttpServletHelper.getUserToken(request));

		if (RestServiceResult.CODE_SUCCESS == user.getCode()) {

			SysUser userInfo = user.getData();

			if (null != userInfo) {

				configColumns = (String[]) MapCache.get(userInfo.getId() + "_" + FRONT_B_TABLE_ID);

			} else {

				ExceptionLogger.error("OragnizationController#getBOrgList", "未获取到当前用户信息！");
			}

		} else {

			ExceptionLogger.error("OragnizationController#getBOrgList", "未获取到当前用户信息！");
		}

		List<String> showColumns = (configColumns == null || configColumns.length == 0)
				? OrgTableFieldEnum.getDefaultShowColumnEN() : Arrays.asList(configColumns);

		String[] additionalColumns = { "orgId" };

		List<Map<String, Object>> orgList = orgService.getOrgListByConditionForPage(null, showColumns,
				additionalColumns, condition, page);
		return new RestServiceResult<List<Map<String, Object>>>(page.getTotalCount(), orgList);

	}

	@ApiOperation(value = "获取高级搜索条件", httpMethod = "GET", produces = "application/json")
	@RequestMapping(value = "/getAdvancedConditionColumns.json", method = RequestMethod.GET)
	public RestServiceResult<List<OptionalColumn>> getAdvancedConditionColumns() {

		return new RestServiceResult<List<OptionalColumn>>(OrgTableFieldEnum.getAdvancedConditionColumns());

	}

	@ApiOperation(value = "获取表头列", httpMethod = "GET", produces = "application/json")
	@RequestMapping(value = "/getOptionalColums.json", method = RequestMethod.GET)
	public RestServiceResult<List<OptionalColumn>> getOptionalColums() {

		return new RestServiceResult<List<OptionalColumn>>(OrgTableFieldEnum.getOptionalColumns());

	}

	@ApiOperation(value = "自定义展示列", httpMethod = "POST", produces = "application/json")
	@RequestMapping(value = "/addBColumns.json", method = RequestMethod.POST)
	public RestServiceResult<Object> addBColumns(
			@ApiParam(required = true, name = "columns", value = "展示列数组") @RequestParam(value = "columns", required = true) String[] columns,
			HttpServletRequest request) {

		RestServiceResult<SysUser> user = xypjRemoteBaseService.getCurrentUser(HttpServletHelper.getUserToken(request));

		if (RestServiceResult.CODE_SUCCESS == user.getCode()) {

			SysUser userInfo = user.getData();

			if (null != userInfo && userInfo.getId() != null) {

				MapCache.set(userInfo.getId() + "_" + FRONT_B_TABLE_ID, columns);
			} else {

				ExceptionLogger.error("OragnizationController#addBColumns", "未获取到当前用户信息！");
			}

		} else {

			ExceptionLogger.error("OragnizationController#addBColumns", "未获取到当前用户信息！");
		}

		return new RestServiceResult<Object>();

	}

	@ApiOperation(value = "导出列表", httpMethod = "GET")
	@RequestMapping("/bExport.json")
	public void bExport(
			@ApiParam(required = true, name = "condition", value = "搜索条件") @RequestParam(value = "condition", defaultValue = "", required = true) String condition,
			@ApiParam(required = true, name = "columnEN", value = "导出列") @RequestParam(value = "columnEN", required = true) String columnEN,
			HttpServletResponse response, HttpServletRequest request, Page page) throws IOException {

		page.setLimit(1000);

		List<String> columns = JSONArray.parseArray(columnEN, String.class);

		List<Map<String, Object>> data = orgService.getOrgListByConditionForPage(null, columns, null, condition, page);

		List<OptionalColumn> optionalColumns = OrgTableFieldEnum.getOptionalColumns();

		ExcelUtil.downloadExcel(response, data, "机构列表", "机构列表", columns, optionalColumns);
	}

	@RequestMapping(value = "/getOrgDetail.json", method = RequestMethod.GET)
	@ApiOperation(value = "获取组织详情", httpMethod = "GET", produces = "application/json")
	public RestServiceResult<Object> getOrgDetail(
			@ApiParam(required = true, name = "orgId", value = "关联机构编号") @RequestParam(required = true) String orgId) {

		Map<String, Object> result = orgService.getDetail(orgId);

		return new RestServiceResult<Object>(result);

	}

	@RequestMapping(value = "/getProfessionals.json", method = RequestMethod.GET)
	@ApiOperation(value = "获取专业人员", httpMethod = "GET", produces = "application/json")
	public RestServiceResult<List<Personnel>> getProfessionals(
			@ApiParam(required = true, name = "orgId", value = "关联机构编号") @RequestParam(required = true) String orgId) {

		List<Personnel> professionals = orgService.getPersonnels(orgId, OrgConstant.PERSONNEL_TYPE_PROFESSIONAL);
		return new RestServiceResult<List<Personnel>>(professionals);

	}

	@RequestMapping(value = "/getManagers.json", method = RequestMethod.GET)
	@ApiOperation(value = "获取管理人员", httpMethod = "GET", produces = "application/json")
	public RestServiceResult<List<Personnel>> getManagers(
			@ApiParam(required = true, name = "orgId", value = "关联机构编号") @RequestParam(required = true) String orgId) {

		List<Personnel> managers = orgService.getPersonnels(orgId, OrgConstant.PERSONNEL_TYPE_MANAGER);
		return new RestServiceResult<List<Personnel>>(managers);

	}

	@RequestMapping(value = "/deletePersonnel.json", method = RequestMethod.POST)
	@ApiOperation(value = "刪除人员", httpMethod = "POST", produces = "application/json")
	public RestServiceResult<String> deletePersonnel(
			@ApiParam(required = true, name = "id", value = "人员编号") @RequestParam(required = true) String id) {

		orgService.deletePersonnels(id);
		return new RestServiceResult<>();

	}

	@RequestMapping(value = "/getICardFPic.png", method = RequestMethod.GET)
	@ApiOperation(value = "获取身份证正图片", httpMethod = "GET", produces = "image/*")
	public void getICardFPic(
			@ApiParam(required = true, name = "id", value = "人员编号") @RequestParam(required = true) String id,
			HttpServletResponse response) throws Exception {

		Personnel personnel = orgService.getPersonnelById(id);

		byte[] data = orgService.getPic(personnel.getIdCardFPic());

		IOUtils.write(data, response.getOutputStream());

	}

	@RequestMapping(value = "/getICardBPic.png", method = RequestMethod.GET)
	@ApiOperation(value = "获取身份证反面图片", httpMethod = "GET", produces = "image/*")
	public void getICardBPic(
			@ApiParam(required = true, name = "id", value = "人员编号") @RequestParam(required = true) String id,
			HttpServletResponse response) throws Exception {

		Personnel personnel = orgService.getPersonnelById(id);

		byte[] data = orgService.getPic(personnel.getIdCardBPic());

		IOUtils.write(data, response.getOutputStream());

	}

	@RequestMapping(value = "/getCertificate.png", method = RequestMethod.GET)
	@ApiOperation(value = "获取资质证书", httpMethod = "GET", produces = "image/*")
	public void getCertificate(
			@ApiParam(required = true, name = "id", value = "人员编号") @RequestParam(required = true) String id,
			HttpServletResponse response) throws Exception {

		Personnel personnel = orgService.getPersonnelById(id);

		byte[] data = orgService.getPic(personnel.getCertification());

		IOUtils.write(data, response.getOutputStream());

	}

	@RequestMapping(value = "/getAccountCertificate.png", method = RequestMethod.GET)
	@ApiOperation(value = "银行开户证明", httpMethod = "GET", produces = "image/*")
	public void getAccountCertificate(
			@ApiParam(required = true, name = "id", value = "组织编号") @RequestParam(required = true) String id,
			HttpServletResponse response) throws Exception {

		Organization org = orgService.getOrgById(id);

		byte[] data = orgService.getPic(org.getAccountCertificate());

		IOUtils.write(data, response.getOutputStream());

	}

	@RequestMapping(value = "/getBusinessLicence.png", method = RequestMethod.GET)
	@ApiOperation(value = "营业执照", httpMethod = "GET", produces = "image/*")
	public void getBusinessLicence(
			@ApiParam(required = true, name = "id", value = "组织编号") @RequestParam(required = true) String id,
			HttpServletResponse response) throws Exception {

		Organization org = orgService.getOrgById(id);

		byte[] data = orgService.getPic(org.getBusinessLicence());

		IOUtils.write(data, response.getOutputStream());

	}

	@RequestMapping(value = "/getCommitmentLetter.png", method = RequestMethod.GET)
	@ApiOperation(value = "信用承诺书", httpMethod = "GET", produces = "image/*")
	public void getCommitmentLetter(
			@ApiParam(required = true, name = "id", value = "组织编号") @RequestParam(required = true) String id,
			HttpServletResponse response) throws Exception {

		Organization org = orgService.getOrgById(id);

		byte[] data = orgService.getPic(org.getCommitmentLetter());

		IOUtils.write(data, response.getOutputStream());

	}

	@RequestMapping(value = "/getOrgCodeCertificate.png", method = RequestMethod.GET)
	@ApiOperation(value = "组织机构代码证", httpMethod = "GET", produces = "image/*")
	public void getOrgCodeCertificate(
			@ApiParam(required = true, name = "id", value = "组织编号") @RequestParam(required = true) String id,
			HttpServletResponse response) throws Exception {

		Organization org = orgService.getOrgById(id);

		byte[] data = orgService.getPic(org.getOrgCodeCertificate());

		IOUtils.write(data, response.getOutputStream());

	}

	@RequestMapping(value = "/getOrgCrSample.png", method = RequestMethod.GET)
	@ApiOperation(value = "企业信用评价样本", httpMethod = "GET", produces = "image/*")
	public void getOrgCrSample(
			@ApiParam(required = true, name = "id", value = "组织编号") @RequestParam(required = true) String id,
			HttpServletResponse response) throws Exception {

		Organization org = orgService.getOrgById(id);

		byte[] data = orgService.getPic(org.getOrgCrSample());

		IOUtils.write(data, response.getOutputStream());

	}

	@RequestMapping(value = "/getTaxRegisterLicence.png", method = RequestMethod.GET)
	@ApiOperation(value = "获取税务登记证", httpMethod = "GET", produces = "image/*")
	public void getTaxRegisterLicence(
			@ApiParam(required = true, name = "id", value = "组织编号") @RequestParam(required = true) String id,
			HttpServletResponse response) throws Exception {

		Organization org = orgService.getOrgById(id);

		byte[] data = orgService.getPic(org.getTaxRegisterLicence());

		IOUtils.write(data, response.getOutputStream());

	}

	@RequestMapping(value = "/getRegulator.png", method = RequestMethod.GET)
	@ApiOperation(value = "制度标准", httpMethod = "GET", produces = "image/*")
	public void getRegulator(
			@ApiParam(required = true, name = "id", value = "组织编号") @RequestParam(required = true) String id,
			HttpServletResponse response) throws Exception {

		Organization org = orgService.getOrgById(id);

		byte[] data = orgService.getPic(org.getRegulator());

		IOUtils.write(data, response.getOutputStream());

	}

	@ApiOperation(value = "获取后台logo", httpMethod = "GET", produces = "image/*")
	@RequestMapping(value = "/getSysLogo.png", method = RequestMethod.GET)
	public void getSysLogo(
			@ApiParam(name = "orgId", value = "关联机构编号", required = true) @RequestParam(required = true) String orgId,
			HttpServletResponse response) throws Exception {

		Element element = orgService.getElement(orgId);

		byte[] data = orgService.getPic(element.getSysLogo());

		IOUtils.write(data, response.getOutputStream());

	}

	@ApiOperation(value = "获取后台logo缩放", httpMethod = "GET", produces = "image/*")
	@RequestMapping(value = "/getScalingSysLogo.png", method = RequestMethod.GET)
	public void getScalingSysLogo(
			@ApiParam(name = "orgId", value = "关联机构编号", required = true) @RequestParam(required = true) String orgId,
			HttpServletResponse response) throws Exception {

		Element element = orgService.getElement(orgId);

		byte[] data = orgService.getPic(element.getScalingSysLogo());

		IOUtils.write(data, response.getOutputStream());

	}

}
